package com.sunny.zkbase;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

/**
 * @Author zsunny
 * @Date 2018/9/12 10:23
 * @Mail zsunny@yeah.net
 */

/**
 * 测试多次对一个node加watcher，随后改变该node看watcher响应几次
 */
public class MultiWatcher {

    private static final String DEFAULT_HOST = "222.201.145.179";
    private static final int DEFAULT_PORT = 5055;
    private CountDownLatch countDownLatch = new CountDownLatch(1);
    private ZooKeeper zk;

    public MultiWatcher(String host, int port) throws IOException, InterruptedException {
        zk = new ZooKeeper(host+":"+port, 20000,
                watchedEvent -> {
                    System.out.println("连接成功");
                    countDownLatch.countDown();
                });
        countDownLatch.await();
    }

    public void createNode(String path, String data) throws KeeperException, InterruptedException {
        zk.create(path, data.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
    }

    public void addWatcher(String path) throws KeeperException, InterruptedException {
        zk.exists(path, watchedEvent -> {
            System.out.println("改变啦");
        });
    }

    public void setData(String path, String data) throws KeeperException, InterruptedException {
        zk.setData(path, data.getBytes(), -1);
    }

    public static void main(String[] args) {

        String node = "/aaa";
        try {
            MultiWatcher multiWatcher = new MultiWatcher(DEFAULT_HOST, DEFAULT_PORT);
//            multiWatcher.createNode(node, "");
            multiWatcher.addWatcher(node);
            multiWatcher.setData(node, "aa");
            multiWatcher.addWatcher(node);
            multiWatcher.setData(node, "ss");
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (KeeperException e) {
            e.printStackTrace();
        }

    }
}
